package com.chen.springboot.config;

import com.auth0.jwt.JWT;
import com.chen.springboot.entity.User;
import com.chen.springboot.service.IUserService;
import com.chen.springboot.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    private static IUserService staticUserService;

    @Resource
    private IUserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    //    添加端点，网页连接websocket
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        /**
         * 将ws/eq路径注册为stomp端点，用户连接这个端点，就可以进行通讯
         * 允许跨域
         * 使用socketjs去连接
         */
        registry.addEndpoint("/ws/ep").withSockJS();
    }


    /**
     * 输入通道参数配置
     *
     * @param registration
     */

    public void configureClientInboundChannel(ChannelRegistration registration, HttpServletRequest request) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
//       判断是否为链接，如果是，需要获取token,并设置用户对象
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    if (!StringUtils.isEmpty(token)) {
                        String authToken = request.getHeader("token");
                        String userId = JWT.decode(authToken).getAudience().get(0);
                        User user = staticUserService.getById(Integer.valueOf(userId));
                    }
                }
                return message;
            }
        });
    }

    /**
     * 配置消息代理
     *
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
//        配置代理域，可以配置多个 可以在配置域上向客户端推送消息

        registry.enableSimpleBroker("/queue");
    }
}
